﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Windows.Media.Imaging;
using ImageTools;
using ImageTools.IO.Gif;
using ImageTools.IO.Jpeg;

namespace EarthWatchers.SL.TIG
{
    public class TigUserinfo
    {
        public string Username { get; set; }
        public string Name { get; set; }
        public string Joined { get; set; }
        public string Country { get; set; }
        public List<string> Friends { get; set; }
        public BitmapImage AvatarSmall { get; set; }
        public BitmapImage AvatarBig { get; set; }
        public BitmapImage CountryFlag { get; private set; }

        public TigUserinfo()
        {
            Friends = new List<string>();
            CountryFlag = new BitmapImage(); //Needed, there is a delay when converting the flag in UI will be null, now updates properly after setSource()
        }

        /// <summary>
        /// Set the bitmapimage for the country flag
        /// Because TIG has the flags in .gif and Silverlight doesn't support this it has to be converted to jpg
        /// </summary>
        /// <param name="url">url to the .gif flag image</param>
        public void SetFlag(string url)
        {
            var newUrl = url.Replace("cdn.", "");
            var client = new WebClient();
            client.OpenReadCompleted += ClientOpenReadCompleted;
            client.OpenReadAsync(new Uri(newUrl));           
        }

        //Receive flag stream
        private void ClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                var gd = new GifDecoder();
                var img = new ExtendedImage();

                gd.Decode(img, e.Result);

                var jpeg = new JpegEncoder();

                using (var stream = new MemoryStream())
                {
                    jpeg.Encode(img, stream);
                    CountryFlag.SetSource(stream);
                }
            }
            catch (Exception)
            {
            }
        }
    }
}
